﻿angular.module('app')
    .controller('AppCtrl', ['$rootScope',
        "$scope", "WorkContextSrv", "$state", 'TopicSrv', 'TaskSrv', function ($rootScope, $scope, workContextSrv, $state, topicSrv, taskSrv) {
         
            //user menu
            $scope.userMenu = workContextSrv.getCurrentUser().userPages;

            //Get current username
            var userName = workContextSrv.getCurrentUser().userName;

            function loadUserData() {
                $scope.username = userName;
                $scope.useravatar = workContextSrv.getCurrentUser().photoPath;
            }

            //load user data
            loadUserData();

            //handle 'userSignIn' event when user signin then reload user data from webStorage
            $rootScope.$on("userSignIn", function () {
                loadUserData();
            });

            //go to task page
            $scope.goToTask = function () {
                if ($state.current.name === 'task') {
                    $rootScope.$broadcast("getTaskCount", false);
                    $rootScope.$broadcast("reloadTasks");
                } else {
                    $state.go("task");
                }
                $scope.$emit("clearTaskCount");
            };

            //go to home page
            $scope.goToHome = function () {
                if ($state.current.name === 'home' || $state.current.name === 'default') {
                    $rootScope.$broadcast("reloadTopics");
                } else {
                    $state.go("home");
                }
                $scope.$emit("clearTopicCount");
            };

            $scope.page = {
                current: {
                    name: $rootScope.currentPageName
                },
                isActive: function (pagename) {
                    var sysPageName = this.current.name;
                    if (sysPageName === 'default') {
                        sysPageName = 'Home';
                    }
                    return angular.lowercase(sysPageName) === angular.lowercase(pagename);
                }
            };

            $scope.$watch("currentPageName", function () {
                $scope.page.current.name = $rootScope.currentPageName;
            });
            
            //TaskCount
            $scope.taskCount = {
                total: 0,
                blink: false,
                previous: 0,
                first: true,
                onLoading: false
            };

            $scope.$on("decreaseTaskCount", function (e, params) {
                if ($scope.taskCount.total > 0) {
                    $scope.taskCount.total = $scope.taskCount.total - params;
                    $scope.taskCount.previous = $scope.taskCount.total;
                }
            });

            //handle 'clearTaskCount' event, set taskcount to 0
            $scope.$on("clearTaskCount", function () {
                $scope.taskCount.previous = $scope.taskCount.total;
                $scope.taskCount.blink = false;
            });

            //handle 'getTaskCount' event, get task count
            $scope.$on("getTaskCount", function (e, params) {
                //Check authenticated
                if (workContextSrv.isAuthenticated() && !$scope.taskCount.onLoading && $state.current.name !== 'signin') {
                    $scope.taskCount.onLoading = true;
                    //get topic count
                    taskSrv.getTasksCount(userName).success(function (data, status) {
                        $scope.taskCount.total = data;
                        $scope.$emit("taskBlink", params);
                        $scope.taskCount.onLoading = false;
                    }).error(function () {
                        //clear task count
                        $scope.$emit("clearTaskCount");
                        $scope.taskCount.onLoading = false;
                    });
                }
            });

            $scope.$on("taskBlink", function (e, params) {
                if (params) {
                    if (!$scope.taskCount.first && $scope.taskCount.previous != $scope.taskCount.total && $scope.taskCount.total > 0) {
                        //show blink effect
                        $scope.taskCount.blink = true;
                    } else {
                        $scope.taskCount.first = false;
                        $scope.taskCount.blink = false;
                    }
                } else {
                    $scope.taskCount.blink = false;
                }
                $scope.taskCount.previous = $scope.taskCount.total;
            });

            //Topic new count
            $scope.topicCount = {
                total: 0,
                blink: false,
                previous: 0,
                onLoading: false
            };

            //handle 'clearTopicCount' event, set topiccount to 0
            $scope.$on("clearTopicCount", function () {
                $scope.topicCount.total = 0;
                $scope.topicCount.previous = 0;
                $scope.topicCount.blink = false;
            });

            //handle 'getTopicCount' event, get topic count
            $scope.$on("getTopicCount", function (e, p) {
                //Check authenticated
                if (workContextSrv.isAuthenticated() && !$scope.topicCount.onLoading && $state.current.name !== 'signin') {

                    $scope.topicCount.onLoading = true;
                    //get topic count
                    topicSrv.getTopicNewCount(userName).success(function (data, status) {
                        //if($state.current.name !== 'home' && $state.current.name !== 'default')
                        //{
                        //    $scope.topicCount.total = data;
                        //}
                        $scope.topicCount.total = data;
                        $scope.topicCount.onLoading = false;
                    }).error(function () {
                        //clear topic count
                        $scope.$emit("clearTopicCount");
                        $scope.topicCount.onLoading = false;
                    });
                }
            });

            //watch task count change
            $scope.$watch("topicCount.total", function () {
                if ($scope.topicCount.previous != $scope.topicCount.total && $scope.topicCount.total > 0) {
                    //save previous data
                    $scope.topicCount.previous = $scope.topicCount.total;
                    //show blink effect
                    $scope.topicCount.blink = true;

                    topicSrv.removeCache();
                } else {
                    $scope.topicCount.blink = false;
                }
            });

        }
    ]).controller('LoginCtrl', ['$rootScope',
        "$scope", "WorkContextSrv", "$state", "UserSrv", function ($rootScope, $scope, workContextSrv, $state, userSrv) {
            $scope.errorMessage = "";
            $scope.showError = false;
            $scope.onSubmitting = false;
            $scope.user = { userName: '', password: '', remember: false };
            $scope.validate = function (field, type) {
                if (type === 'required') {
                    return ($scope.showError && (typeof $scope.loginform[field].$viewValue === 'undefined' || $scope.loginform[field].$viewValue === ''));
                }
                return false;
            };
            $scope.doLogin = function (user) {
                $scope.showError = true;
                $scope.errorMessage = "";
                if (user.username != '' && user.password != '' && $scope.loginform.$valid) {
                    $scope.onSubmitting = true;
                    userSrv.authorize(user.username, user.password, user.remember).success(function (data, status) {
                        $scope.onSubmitting = false;
                        if (data == 'true') {
                            $scope.onSubmitting = true;
                            userSrv.getUserByName(user.username).then(function (dt) {
                                workContextSrv.setCurrentUser(dt);
                                $rootScope.$broadcast("userSignIn");
                                //$state.go("home");
                                location.href = location.href.split('#')[0];
                            });
                            //userSrv.getUserByName(user.username).success(function (dt, st) {
                            //    workContextSrv.setCurrentUser(dt);
                            //    $rootScope.$broadcast("userSignIn");
                            //    //$state.go("home");
                            //    location.href = location.href.split('#')[0];

                            //}).error(function (dt, st) {
                            //    $scope.onSubmitting = false;
                            //    $scope.showError = true;
                            //    $scope.errorMessage = dt.message;
                            //});
                        } else {
                            $scope.errorMessage = "The username or password provided is incorrect!";
                            $scope.onSubmitting = false;
                            $scope.showError = true;
                        }
                    }).error(function (data, status) {
                        $scope.showError = true;
                        $scope.errorMessage = data.message;
                        $scope.onSubmitting = false;
                    });
                }
            };
        }
    ]);